package cn.kgc.tangcco.controller;

import cn.kgc.tangcco.model.ResponseText;
import cn.kgc.tangcco.model.ResultCode;
import cn.kgc.tangcco.utils.fastdfs.BaseFastDFSUtil;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author 李昊哲
 * @Description fastdfs
 * @date 2020/12/3 上午10:26
 */
@RestController
@RequestMapping(value = "/fdfs")
public class FdfsContrller {

    @Value("${fdfs_storage_proxy.protocol}")
    private String fdfs_storage_proxy_protocol;

    @Value("${fdfs_storage_proxy.domain}")
    private String fdfs_storage_proxy_domain;

    @Value("${fdfs_storage_proxy.port}")
    private String fdfs_storage_proxy_port;

    @GetMapping(value = "/hello")
    public String hello() {
        return "桃李不言下自成蹊";
    }

    @GetMapping(value = "/proxy")
    public String proxy() {
        return fdfs_storage_proxy_protocol + fdfs_storage_proxy_domain + ":" + fdfs_storage_proxy_port;
    }

    @RequestMapping(value = "/upload")
    public ResponseText<String> upload(@RequestParam("header") MultipartFile multipartFile) {
        // 存储服务器web服务地址
        String fdfs_storage_proxy_url = fdfs_storage_proxy_protocol + fdfs_storage_proxy_domain + ":" + fdfs_storage_proxy_port;
        // 封装返回数据
        ResponseText<String> ResponseText = new ResponseText<String>(ResultCode.DATA_ERROR.getCode(), ResultCode.DATA_ERROR.getMsg(), null);
        // 默认上传失败
        // 获取源文件名字
        String originalFilename = multipartFile.getOriginalFilename();
        //获得源文件后缀
        String suffix = FilenameUtils.getExtension(originalFilename);
        // 文件上传
        try {

            String url = BaseFastDFSUtil.upload(fdfs_storage_proxy_url, multipartFile.getInputStream(), suffix);
            // 上传成功
            ResponseText.setCode(ResultCode.SUCCESS.getCode());
            ResponseText.setMsg(ResultCode.SUCCESS.getMsg());
            // 服务器端文件地址
            ResponseText.setData(url);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            return ResponseText;
        }
    }
}
